<?php
namespace app\admin\controller;
use app\model\UserBill as UserBillModel;
use app\model\User as UserModel;
use app\model\Admin as AdminModel;
use think\Db;


class UserBill extends Base
{
    public function __construct(){
        $model = new UserBillModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '收支明细';

        if ( in_array($page_info['action'], ['add','edit']) ) {
            $fields = [
                'collect'=>['name'=>'来源','type'=>'select1','params'=>$model->getCollectList()],
                'amount'=>['name'=>'充值金额','type'=>'text'],
                'remark'=>['name'=>'备注','type'=>'textarea'],
            ];
            $valids = createPageValid($fields);
            $this->assign([
                'fields'=>$fields,
                'valids'=>$valids
            ]);
        }

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function getMap(){
        $map_params = [
            ['key'=>'user_id','type'=>'='],
            ['key'=>'collect','type'=>'=']
        ];
        $map = getSearchParam($map_params,'ub.');

        if (isSearchParam('start_time')) {
            $map[] = ['ub.ctime','>=',strtotime(input('start_time'))];
        }
        if (isSearchParam('end_time')) {
            $map[] = ['ub.ctime','<',strtotime(input('end_time'))];
        }
        if (isSearchParam('user_name')) {
            $user_ids = Db::name('user')->where('truename','like','%'.input('user_name').'%')->column('id');
            $map[] = ['ub.user_id','in',$user_ids];
        }
        return $map;
    }

    public function index(){
        $model = $this->model;
        $map = $this->getMap();
        

        $tmp_users = Db::name('user')->field('id,truename,mobile')->select();
        $users = [];
        foreach ($tmp_users as $k => $vo) {
            $users[$vo['id']] = $vo['truename'].'('.$vo['mobile'].')';
        }

        $search_params = [
            [
                ['key'=>'user_id','name'=>'用户','type'=>'select2_1','params'=>$users],
                ['key'=>'collect','name'=>'来源','type'=>'select1_1','params'=>$model->getCollectList()],
                ['key'=>'start_time','name'=>'开始时间','type'=>'date'],
                ['key'=>'end_time','name'=>'结束时间','type'=>'date'],
                ['key'=>'user_name','name'=>'用户名称','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        $list = $model->alias('ub')->field('ub.*,u.truename as user_name,u.mobile as user_mobile')
        ->join('user u','ub.user_id = u.id','left')
        ->where($map)->order('ub.id','desc')->paginate($page_param);
        $page = $list->render();

        $admins = AdminModel::select();
        $admins = arrayParamExtract($admins,'id','truename');

        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
           $list['data'][$k]['admin_name'] = $admins[$vo['admin_id']];
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    public function export(){
        set_time_limit ( 0 );
        ini_set('memory_limit','40960M');

        $model = $this->model;
        $map = $this->getMap();

        $model = $this->model;
        $list = $model->alias('ub')->field('ub.*,u.name as user_name,u.mobile as user_mobile,u.email as user_email,u.admin_id as user_admin_id,u.pk,u.ctime as user_ctime')
        ->join('user u','ub.user_id = u.id','left')
        // ->where($map)->order('ub.id','asc')->select();
        ->where($map)->order('ub.user_id asc,ub.id asc')->select();

        $admins = AdminModel::select();
        $admins = arrayParamExtract($admins,'id','truename');
        
        $data = [];
        $title = ['日期','用户','手机号','PK（UID）','邮箱','注册时间','所属销售','类型','收入','支出','余额','备注','操作人'];
        foreach ($list as $k => $vo) {
            $tmp = [
                timeDef($vo['ctime'],'','Y-m-d H:i:s'),
                $vo['user_name'],$vo['user_mobile'],$vo['pk'],$vo['user_email'],
                timeDef($vo['user_ctime'],'','Y-m-d H:i:s'),
                $admins[$vo['user_admin_id']],
                $model->getTypeCn($vo['type']),
                $vo['amount'] > 0 ? $vo['amount'] : 0,
                $vo['amount'] < 0 ? $vo['amount'] : 0,
                $vo['balance'],
                $vo['remark'],
                $admins[$vo['admin_id']]
            ];
            $data[] = $tmp;
        }
        exportCsv(date('YmdHis'),$title,$data);
    }

    public function add(){
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'must'=>['user_id','amount','collect'],
                'nomust'=>['remark']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            $save_data['amount'] = floatval($save_data['amount']);

            Db::startTrans();
            try{
                $save_data['admin_id'] = $this->login_user['id'];
                if ( !UserBillModel::saveData($save_data) ) {
                    throw new \Exception("用户费用生成失败");
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("充值成功",url('index',['user_id'=>$save_data['user_id']]));
        }

        $data = Db::name('user')->where('id',input('user_id'))->find();
        return view('save', [
            'data'=>$data
        ]);
    }




   
}
